package com.youdianstar.app.common.util

import com.youdianstar.app.common.ConfigKey
import com.youdianstar.app.common.entity.*
import com.youdianstar.app.common.ex.toJson
import java.lang.Exception


/**
 * File: DataManager
 * Author: 82149 Create: 2021/10/11 18:51
 * Changes (from 2021/10/11)
 * --------------------------------------------------
 * description: 临时数据与缓存数据的 统一处理类
 * ---------------------------------------------------
 *
 */
open class DataManager {
    companion object {
        val instance by lazy { DataManager() }
    }

    private var phoneMac =""

    /**
     * 保存手机id
     */
    fun setPhoneId(phone: String?) {
        phone?.run {
            phoneMac = phone
            SPUtil.getInstance().put("PhoneId", this)
        }
    }

    fun getPhoneId(): String {
        if (StrUtil.isEmpty(phoneMac))
            phoneMac = SPUtil.getInstance().getString("PhoneId", "")
        return phoneMac
    }

    /**
     * 获取token
     */
    fun getToken(): String {
        return if (CacheUtil.instance.getLoginToken()!=null) CacheUtil.instance.getLoginToken()!! else ""
    }


    /**
     * 设置token
     */
    fun setToken(token: String?) {
        token?.let {
            CacheUtil.instance.setLoginToken(it)
        }
    }


    /**
     * token是否存在
     */
    fun isTokenExist(): Boolean {
        return CacheUtil.instance.isLogin()
    }

    private var userInfo: UserInfo? = null

    /**
     * 获取用户
     */
    fun getUser(): UserInfo? {
        return if (null!=userInfo)
            userInfo
        else {
            userInfo = CacheUtil.instance.getUser()
            userInfo
        }
    }

    /**
     * 清空用户数据
     */
    fun clearUser() {
        userInfo = null
        CacheUtil.instance.setUser(null)
        firebaseReady = false
    }

    /**
     * 保存User
     *
     * @param user
     */
    fun saveUser(user: UserInfo) {
        CacheUtil.instance.setUser(user)
        userInfo = user
        userInfo?.let {
            setToken(it.token)
            if (null!=it.code)
                savePhoneCode("${it.code}")
        }
    }

    fun saveCacheUser(){
        userInfo?.let {
            CacheUtil.instance.setUser(it)
        }
    }

    /**保存上次选择的区号*/
    fun savePhoneCode(code: String?) {
        code?.run {
            CacheUtil.instance.setStringValue("PhoneCode",this)
        }
    }

    fun getPhoneCode(): String {
        return CacheUtil.instance.getStringValue("PhoneCode","84")
    }

    /**保存区号+手机号/Email*/
    fun saveAccount(account :Account) {
        CacheUtil.instance.setStringValue("account", account.toJson())
    }

    fun getAccount(): Account? {
        return try {
            val json = CacheUtil.instance.getStringValue("account","")
            GsonUtil.jsonToBean(json,Account::class.java)
        } catch (e : Exception){
            null
        }
    }


    //----------------Firebase init ----------------------------------
    var firebaseReady = false

    //----------------------------------Payment record------------------


    /**
     * 记录租借的付款类型
     * @param lastPayType 最近一次支付方式
     */
    fun saveLastPayType(lastPayType: Int) {
        SPUtil.getInstance().put("lastPayType"+userInfo?.id,lastPayType)
    }

    /**
     * 获取最近的支付方式
     */
    fun getLastPayType(): Int {
        return SPUtil.getInstance().getInt("lastPayType"+userInfo?.id,0)
    }


    //----------------System Config ----------------------------------

    var isRequestConfig = false

    private var country :String = "" //国家代码
    private var currency :String = ""//显示货币代码
    private var symbol :String = "" //要不显示货币符号

    fun countryTx():String{
        return if (StrUtil.isEmpty(country)) "IT" else country
    }

    fun symbolTx():String{
        return if (StrUtil.isEmpty(symbol)) "₫" else symbol
    }

    fun currencyTx():String{
        return if (StrUtil.isEmpty(currency)) "EUR" else currency
    }

    private var configs: List<ConfigItem>? = null

    fun saveConfig(data: List<ConfigItem>?) {
        if (!data.isNullOrEmpty()) {
            configs = data
            CacheUtil.instance.setSystemConfig(data)
            try {
                currency = ""
                for (it in data) {
                    if (it.key == ConfigKey.CURRENCY) {
                        val json = it.value
                        val currencyInfo : CurrencyInfo = GsonUtil.jsonToBean(json,CurrencyInfo::class.java)
                        country = currencyInfo.country
                        currency = currencyInfo.currency
                        symbol = currencyInfo.symbol
                        break
                    }
                }
            } catch (e:Exception){
                e.printStackTrace()
            }
        }
    }

    fun getConfig(key: String): String {
        val configList =  CacheUtil.instance.getSystemConfig()
        if (configs == null && configList ==null) {
            return ""
        }
        var keyValue :String? = ""
        configList?.let { lists ->
            val items = configs ?: lists
            val map = items.associateBy { it.key }.withDefault { ConfigItem("", "", "", "") }
            keyValue = map[key]?.value
            //return map[key]?.value ?: ""
        }
        return keyValue ?: ""
    }

    //------------------商户权限相关方法------------------
    
    /**
     * 检查用户是否具有商户权限
     * @return true-有商户权限 false-无商户权限
     */
    fun hasMerchantPermission(): Boolean {
        val user = getUser()
        return user?.let { userInfo ->
            // 用户类型为商户用户(3) 或者 是网点账号
            userInfo.type == 3 || userInfo.isBranch
        } ?: false
    }
    
    /**
     * 检查用户是否为商户用户类型
     * @return true-是商户用户 false-不是商户用户
     */
    fun isMerchantUser(): Boolean {
        val user = getUser()
        return user?.type == 3
    }
    
    /**
     * 检查用户是否为网点账号
     * @return true-是网点账号 false-不是网点账号
     */
    fun isBranchAccount(): Boolean {
        val user = getUser()
        return user?.isBranch == true
    }
}